<template>
  <view class="publish">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <text class="back" @click="goBack">＜</text>
      <text class="nav-title">发布需求</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 表单内容 -->
    <scroll-view class="form-container" scroll-y="true" :style="{ height: scrollHeight + 'px' }">
      <!-- 辅导项目 -->
      <view class="form-item">
        <text class="label">辅导项目</text>
        <view class="btn-group">
          <view v-for="item in types" :key="item" :class="['btn', form.tutoringItem === item ? 'active' : '']" @click="form.tutoringItem = item">{{ item }}</view>
        </view>
      </view>

      <!-- 学习阶段 -->
      <view class="form-item">
        <text class="label">学习阶段</text>
        <view class="btn-group">
          <view v-for="item in stages" :key="item" :class="['btn', form.studyStage === item ? 'active' : '']" @click="form.studyStage = item">{{ item }}</view>
        </view>
      </view>

      <!-- 学习位置 -->
      <view class="form-item">
        <text class="label">学习位置</text>
        <view class="btn-group">
          <view v-for="item in locations" :key="item" :class="['btn', form.studyPlace === item ? 'active' : '']" @click="form.studyPlace = item">{{ item }}</view>
        </view>
      </view>

      <!-- 学习学校 -->
      <view class="form-item">
        <text class="label">学习学校</text>
        <textarea
          v-model="form.studySchool"
          placeholder="请输入自己的学校，不展示，仅做信息匹配"
          class="textarea single-line"
          maxlength="50"
          :auto-height="false"
        />
      </view>

      <!-- 学习专业 -->
      <view class="form-item">
        <text class="label">学习专业</text>
        <textarea
          v-model="form.studyMajor"
          placeholder="请输入自己的专业"
          class="textarea single-line"
          maxlength="50"
          :auto-height="false"
        />
      </view>

      <!-- 预算区间 -->
      <view class="form-item">
        <text class="label">预算区间</text>
        <view class="budget-group">
          <textarea
            v-model="form.budgetMin"
            placeholder="最低"
            class="textarea budget single-line"
            maxlength="10"
            :auto-height="false"
          />
          <text class="budget-sep">-</text>
          <textarea
            v-model="form.budgetMax"
            placeholder="最高"
            class="textarea budget single-line"
            maxlength="10"
            :auto-height="false"
          />
          <text class="budget-unit">元</text>
        </view>
      </view>

      <!-- 老师要求 -->
      <view class="form-item">
        <text class="label">老师要求</text>
        <view class="sub-label">老师学历</view>
        <view class="btn-group">
          <view v-for="item in teacherDegrees" :key="item" :class="['btn', form.teacherLevel === item ? 'active' : '']" @click="form.teacherLevel = item">{{ item }}</view>
        </view>
        <view class="sub-label">是否留学</view>
        <view class="btn-group">
          <view v-for="item in abroadOptions" :key="item" :class="['btn', form.teacherAbroad === item ? 'active' : '']" @click="form.teacherAbroad = item">{{ item }}</view>
        </view>
      </view>

      <!-- 需求描述 -->
      <view class="form-item">
        <text class="label">需求描述</text>
        <textarea v-model="form.requirementText" placeholder="请输入辅导需求（500字）" class="textarea" maxlength="500" />
        <view class="char-count">{{ form.requirementText.length }}/500</view>
      </view>

      <!-- 其他说明 -->
      <view class="form-item">
        <text class="label">其他说明</text>
        <textarea v-model="form.comment" placeholder="请输入（500字）" class="textarea" maxlength="500" />
        <view class="char-count">{{ form.comment.length }}/500</view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-container">
        <button type="primary" class="submit-btn" @click="submit" :disabled="!canSubmit">提交需求</button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useOrderStore } from '../../../store/order.js'
import { requirementApi, constants } from '../../../api'

const orderStore = useOrderStore()

const types = ['论文', '作业', '保研', '考研', '其他']
const stages = ['本科', '硕士', '博士']
const locations = ['国内', '国外']
const teacherDegrees = ['本科', '硕士', '博士', '高校老师']
const abroadOptions = ['是', '不要求']
const scrollHeight = ref(600)

// 原生input不需要focus状态控制

const form = ref({
  tutoringItem: '',
  studyStage: '',
  studyPlace: '',
  studySchool: '',
  studyMajor: '',
  budgetMin: '',
  budgetMax: '',
  teacherLevel: '',
  teacherAbroad: '',
  requirementText: '',
  comment: ''
})

const loading = ref(false)

// 检查表单是否可以提交
const canSubmit = computed(() => {
  return form.value.tutoringItem &&
         form.value.studyStage &&
         form.value.studyPlace &&
         form.value.studySchool &&
         form.value.studyMajor &&
         form.value.budgetMin &&
         form.value.budgetMax &&
         form.value.requirementText.trim()
})

const goBack = () => {
  uni.navigateBack()
}

// 原生input不需要额外的焦点处理函数

const submit = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完善必填信息',
      icon: 'none'
    })
    return
  }

  // 验证预算区间
  if (parseInt(form.value.budgetMin) >= parseInt(form.value.budgetMax)) {
    uni.showToast({
      title: '预算区间设置有误',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '确认提交',
    content: '确定要提交这个需求吗？',
    success: async (res) => {
      if (res.confirm) {
        await publishRequirement()
      }
    }
  })
}

// 发布需求
const publishRequirement = async () => {
  if (loading.value) return

  loading.value = true
  try {
    // 构建需求数据
    const requirementDto = {
      tutoringItem: getTutoringItemValue(form.value.tutoringItem),
      studyStage: getStudyStageValue(form.value.studyStage),
      studyPlace: getStudyPlaceValue(form.value.studyPlace),
      studySchool: form.value.studySchool,
      studyMajor: form.value.studyMajor,
      budgetMin: parseInt(form.value.budgetMin),
      budgetMax: parseInt(form.value.budgetMax),
      teacherLevel: getTeacherLevelValue(form.value.teacherLevel),
      teacherAbroad: getTeacherAbroadValue(form.value.teacherAbroad),
      requirementText: form.value.requirementText,
      comment: form.value.comment
    }

    const response = await requirementApi.addRequirement(requirementDto)

    if (response.code === '1000') {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })

      setTimeout(() => {
        // 返回到订单列表页面
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: response.message || '提交失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('发布需求失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 辅助方法：将文本转换为对应的常量值
const getTutoringItemValue = (text) => {
  const map = { '论文': constants.TUTORING_ITEM.THESIS, '作业': constants.TUTORING_ITEM.HOMEWORK, '保研': constants.TUTORING_ITEM.POSTGRADUATE, '考研': constants.TUTORING_ITEM.GRADUATE_EXAM, '其他': constants.TUTORING_ITEM.OTHER }
  return map[text] || constants.TUTORING_ITEM.OTHER
}

const getStudyStageValue = (text) => {
  const map = { '本科': constants.STUDY_STAGE.UNDERGRADUATE, '硕士': constants.STUDY_STAGE.MASTER, '博士': constants.STUDY_STAGE.DOCTOR }
  return map[text] || constants.STUDY_STAGE.UNDERGRADUATE
}

const getStudyPlaceValue = (text) => {
  const map = { '国内': constants.STUDY_PLACE.DOMESTIC, '国外': constants.STUDY_PLACE.ABROAD }
  return map[text] || constants.STUDY_PLACE.DOMESTIC
}

const getTeacherLevelValue = (text) => {
  const map = { '本科': constants.TEACHER_LEVEL.UNDERGRADUATE, '硕士': constants.TEACHER_LEVEL.MASTER, '博士': constants.TEACHER_LEVEL.DOCTOR, '高校老师': constants.TEACHER_LEVEL.PROFESSOR }
  return map[text] || constants.TEACHER_LEVEL.MASTER
}

const getTeacherAbroadValue = (text) => {
  const map = { '是': constants.TEACHER_ABROAD.YES, '不要求': constants.TEACHER_ABROAD.NO_REQUIREMENT }
  return map[text] || constants.TEACHER_ABROAD.NO_REQUIREMENT
}

onMounted(() => {
  // 计算滚动区域高度
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 120 // 减去导航栏高度
})
</script>

<style scoped>
.publish {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.back {
  font-size: 40rpx;
  color: #333;
  padding: 0 16rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.nav-placeholder {
  width: 48rpx;
  height: 48rpx;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 32rpx;
}

.form-item {
  margin-bottom: 40rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
  font-weight: 600;
}

.sub-label {
  font-size: 26rpx;
  color: #666;
  margin: 24rpx 0 12rpx 0;
  font-weight: 500;
}

.btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-top: 16rpx;
}

.btn {
  padding: 16rpx 32rpx;
  border-radius: 12rpx;
  background: #f8f8f8;
  color: #666;
  font-size: 26rpx;
  border: 2rpx solid #f0f0f0;
  transition: all 0.3s;
}

.btn.active {
  background: #1e98d7;
  color: #fff;
  border-color: #1e98d7;
  font-weight: bold;
}

.input {
  width: 100%;
  border: 2rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #fafafa;
  margin-top: 16rpx;
  box-sizing: border-box;
  /* 确保input可以接收点击事件 */
  pointer-events: auto;
  /* 确保input在正确的层级 */
  position: relative;
  z-index: 1;
  /* 确保input可以获取焦点 */
  -webkit-user-select: auto;
  user-select: auto;
}

.input:focus {
  border-color: #1e98d7;
  background: #fff;
  outline: none;
}

/* 原生input样式 */
.native-input {
  /* 重置浏览器默认样式 */
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  /* 确保在所有平台都能正常工作 */
  border: 2rpx solid #eee !important;
  border-radius: 12rpx !important;
  padding: 20rpx !important;
  font-size: 28rpx !important;
  background: #fafafa !important;
  box-sizing: border-box !important;
  outline: none !important;
}

.native-input:focus {
  border-color: #1e98d7 !important;
  background: #fff !important;
}

/* 单行textarea样式 */
.single-line {
  height: 60rpx !important;
  min-height: 60rpx !important;
  max-height: 60rpx !important;
  line-height: 60rpx !important;
  resize: none !important;
  overflow: hidden !important;
  white-space: nowrap !important;
  text-overflow: ellipsis !important;
}

.single-line.budget {
  width: 160rpx !important;
  height: 60rpx !important;
  min-height: 60rpx !important;
  max-height: 60rpx !important;
  line-height: 60rpx !important;
}

.budget-group {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-top: 16rpx;
}

.budget {
  width: 160rpx;
  flex-shrink: 0;
}

.budget-sep {
  margin: 0 8rpx;
  color: #888;
  font-size: 28rpx;
}

.budget-unit {
  margin-left: 8rpx;
  color: #888;
  font-size: 28rpx;
}

.textarea {
  width: 100%;
  min-height: 160rpx;
  border: 2rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #fafafa;
  margin-top: 16rpx;
  box-sizing: border-box;
  line-height: 1.5;
}

.textarea:focus {
  border-color: #1e98d7;
  background: #fff;
}

.char-count {
  text-align: right;
  color: #999;
  font-size: 24rpx;
  margin-top: 8rpx;
}

.submit-container {
  margin-top: 40rpx;
  padding-bottom: 40rpx;
}

.submit-btn {
  width: 100%;
  font-size: 32rpx;
  height: 96rpx;
  border-radius: 12rpx;
  background: #1e98d7;
  border: none;
  color: #fff;
  font-weight: bold;
}

.submit-btn[disabled] {
  background: #ccc;
  color: #999;
}
</style>